package com.example.demo.common.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.example.demo.common.util.EncryptUtils;
import com.example.demo.modules.service.UserService;
import com.example.demo.modules.vo.UserVo;

public class UserValidation extends AuthorizingRealm {
	private UserService userService;

	public UserValidation(UserService userService) {
		this.userService = userService;
	}

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String userName = String.valueOf(token.getPrincipal());
		UserVo userVo = userService.findUserByName(userName);
		if(userVo == null) {
			throw new AuthenticationException("用户不存在");
		}
		
		ByteSource bytes = ByteSource.Util.bytes(token.getCredentials());
		String password = new String(bytes.getBytes());
		if(!EncryptUtils.validateMd5(password, userVo.getUserSalt(), userVo.getUserPass())) {
			throw new AuthenticationException("密码不正确");
		}
		return new SimpleAuthenticationInfo(userName, password, getName());
	}

}
